package io.renren.modules.h5.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONArray;
import io.renren.common.interceptor.GlobalConstant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.modules.nuaa.dto.*;
import io.renren.modules.nuaa.entity.*;
import io.renren.modules.nuaa.service.*;
import io.renren.modules.sys.dto.SysRegionDTO;
import io.renren.modules.sys.service.SysRegionService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

//@RestController
@Controller
@RequestMapping("/h5")
public class IndexController {

    @Autowired
    private TSignupRecordService tSignupRecordService;
    @Autowired
    private TQuestionService tQuestionService;
    @Autowired
    private TQuestionItemService tQuestionItemService;
    @Autowired
    private TQuestionOptionsService tQuestionOptionsService;
    @Autowired
    private TUserService tUserService;
    @Autowired
    private TNewsService tNewsService;
    @Autowired
    private TCertificateService tCertificateService;
    @Autowired
    private TAboutService tAboutService;
    @Autowired
    private TSignupRecordService signupRecordService;
    @Autowired
    private SysRegionService sysRegionService;
    @Autowired
    private TAddressService tAddressService;

    @Value("${domain}")
    private String domain = "http://localhost/img/";
    @Value("${picDir}")
    private String picDir = "/Users/wanghucheng/Downloads/picture/";

    @RequestMapping(value = "/{url}", method = RequestMethod.GET)
    public String show(@PathVariable("url") String url, HttpServletRequest request) {
        String backUrl = (String)request.getParameter("backUrl");
        request.setAttribute("backUrl", backUrl);
        if("about".equals(url)) {
            TAboutEntity about = tAboutService.selectById(1);
            request.setAttribute("about", about);
        }
        if("show-list".equals(url)){
            List<TNewsDTO> showList = tNewsService.queryNewsList(2L);
            request.setAttribute("showList", showList);
        }else if("news-list".equals(url)){
            String id = request.getParameter("id");
            Long categoryId = 2L;
            if(StringUtils.isNotEmpty(id)) {
                categoryId = Long.parseLong(id);
            }
            List<TNewsDTO> showList = tNewsService.queryNewsList(categoryId);
            request.setAttribute("newsList", showList);
        }else if("signup-list".equals(url)) {
            List<TNewsDTO> showList = tNewsService.queryNewsList(6L);
            request.setAttribute("signupList", showList);
        }else if("addr-list".equals(url)){
            List<TAddressDTO> showList = tAddressService.list(new HashMap<>());
            request.setAttribute("newsList", showList);
        }
        return url;
    }

    /**
     * 注册提交
     * @return
     */
    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> reg(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        Session session = SecurityUtils.getSubject().getSession();
        // 获取openId
        String openId = "000adf";
        String backUrl = request.getParameter("backUrl");
        // todo
        String userName = (String)params.get("userName");
        String idCard = (String)params.get("idCard");
        String company = (String)params.get("company");
        String sex = (String)params.get("sex");
        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(idCard)) {
            return new Result<String>().error("姓名和身份证号不能为空");
        }
        //校验身份证号不能重复
        TUserEntity dto = tUserService.getUserByIdCard(idCard);
        if(dto != null) {
            //return new Result<String>().error("身份证号已经注册");
            session.setAttribute(GlobalConstant.SESSION_USER, dto);
            return new Result<String>().error(201, backUrl);
        }
        dto = new TUserEntity();
        dto.setOpenid(openId);
        dto.setRealName(userName);
        dto.setIdCard(idCard);
        dto.setSex(sex);
        dto.setCompany(company);
        dto.setCreateDate(new Date());
        tUserService.insert(dto);
        session.setAttribute(GlobalConstant.SESSION_USER, dto);
        return new Result<String>().ok(backUrl);
    }

    /**
     * 报名
     * @param dto
     * @return
     */
    @RequestMapping(value = "/subSignup")
    @ResponseBody
    public Result<String> signup(TSignupRecordDTO dto) {
        int cateGoryId = dto.getCategoryId();
        // 1:实践报名 4:教育基地申请 5:俱乐部申请
        if(cateGoryId == 1) {
            // 实践报名，根据姓名和身份证号校验不能重复报名
            String userName = dto.getUserName();
            String idCard = dto.getIdCard();
            TSignupRecordEntity entity = tSignupRecordService.queryIfExist(userName, idCard);
            if(entity != null) {
                return new Result<String>().error("请勿重复报名");
            }
        } else if(cateGoryId == 4) {
            TNewsEntity news = tNewsService.selectById(dto.getNewsId());
            String inviteCode = news.getInviteCode();
            if(StringUtils.isNotEmpty(inviteCode)) {
                if(!inviteCode.equals(dto.getInviteCode())) {
                    return new Result<String>().error("邀请码错误");
                }
            }
            TSignupRecordEntity entity = tSignupRecordService.queryIfExist(dto);
            if(entity != null) {
                return new Result<String>().error("请勿重复报名");
            }
        } else if(cateGoryId == 5) {
            TSignupRecordEntity entity = tSignupRecordService.queryIfExist(dto);
            if(entity != null) {
                return new Result<String>().error("请勿重复报名");
            }
        }
        dto.setSignupDate(new Date());
        tSignupRecordService.save(dto);
        return new Result<String>().ok("报名成功");
    }

    /**
     * 题库列表
     * @param params
     * @param request
     * @return
     */
    @RequestMapping(value = "/exam-list", method = RequestMethod.GET)
    public String examsPage(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletRequest request) {
        PageData<TQuestionDTO> page = tQuestionService.page(params);
        List<TQuestionDTO> list = page.getList();
        for(TQuestionDTO dto : list) {
            HashMap map = MapUtil.newHashMap();
            dto.setQuestionItemList(tQuestionItemService.list(map));
        }
        request.setAttribute("list", page.getList());
        return "exam-list";
    }

    @RequestMapping(value = "/exam/{id}", method = RequestMethod.GET)
    public String exams(@PathVariable("id") String id, HttpServletRequest request) {
        Session session = SecurityUtils.getSubject().getSession();
        System.out.println(session.getTimeout());
        TUserEntity userEntity = (TUserEntity)session.getAttribute(GlobalConstant.SESSION_USER);
        if(userEntity == null) {
            request.setAttribute("backUrl", "/h5/exam/" + id);
            return "login";
        }

        HashMap param = MapUtil.newHashMap();
        param.put("question_id", id);
        List<TQuestionItemDTO> list = tQuestionItemService.list(param);
        for(TQuestionItemDTO dto : list) {
            HashMap map = MapUtil.newHashMap();
            map.put("item_id", dto.getId());
            dto.setOptionsDTOList(tQuestionOptionsService.list(map));
        }
        request.setAttribute("id",id);
        request.setAttribute("exam", list);
        return "exam";
    }

    // 证书查询
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public String query() {
        return "query";
    }

    @RequestMapping(value = "/news/{id}", method = RequestMethod.GET)
    public String news(@PathVariable("id") String id, HttpServletRequest request) {
        TNewsEntity news = tNewsService.selectById(id);
        if (news == null) {
            return "404";
        }

        int categoryId = news.getCategoryId();
        if (categoryId == 2) {
            request.setAttribute("show", news);
            // 航模队表演
            return "show";
        } else if (categoryId == 3 || categoryId == 4 || categoryId == 5) {
            request.setAttribute("news", news);
            // 3公益活动 4教育基地 5俱乐部
            return "news";
        }
        return "exam";
    }

    /**
     * 图片上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ResponseBody
    public Result<Map<String, String>> tinymceUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, String>>().error("上传文件不能为空");
        }
        //上传文件
        String fileName = new Date().getTime() + "";
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String path = picDir + fileName + "." + extension;
        file.transferTo(new File(path));

        Map<String, String> data = new HashMap<>(1);
        data.put("location", domain + fileName + "." + extension);
        return new Result<Map<String, String>>().ok(data);
    }

    @RequestMapping(value = "/submitAnswer", method = RequestMethod.GET)
    @ResponseBody
    public Result<String> submitAnswer(@RequestParam Map<String, Object> params) {
        Session session = SecurityUtils.getSubject().getSession();
        System.out.println(session.getTimeout());
        TUserEntity wxUser = (TUserEntity) session.getAttribute(GlobalConstant.SESSION_WX_USER);
        if (wxUser == null) {
            return new Result<String>().error(401, "请先登录");
        }
        String openId = wxUser.getOpenid();
        TUserEntity userEntity = tUserService.getUserByOpenId(openId);
        if (userEntity == null) {
            return new Result<String>().error("请先注册");
        }
        String id = (String) params.get("id");
        String answers = (String) params.get("answers");
        System.out.println("answers=" + answers);
        // string字符串转json对象
        JSONArray jsonArray = JSONArray.parseArray(answers);
        // json对象转java对象
        List<Map> list = jsonArray.toJavaList(Map.class);
        // answer-1-2  answer-题目id-选项id
        // [{"key":"answer-1-2","val":"2"}]
        Map answerMap = tQuestionItemService.rebuildAnswer(answers);
        tQuestionItemService.submitAnswer(id, answerMap, userEntity.getId().intValue());
        return new Result<String>().ok("答题完成");
    }

    /**
     * 根据分类查看文章列表
     */
    @GetMapping("queryNewsList/{categoryId}")
    public Result<List<TNewsDTO>> queryNewsList(@PathVariable Long categoryId){

        List<TNewsDTO> list = tNewsService.queryNewsList(categoryId);

        return new Result<List<TNewsDTO>>().ok(list);
    }

    /**
     * 查文章详情
     */
    @GetMapping("queryNewsById/{id}")
    public Result<TNewsDTO> queryNewsById(@PathVariable("id") Long id) {
        TNewsDTO data = tNewsService.get(id);

        return new Result<TNewsDTO>().ok(data);
    }

    /**
     * 证书查询
     */
    @RequestMapping(value = "/cer-detail", method = RequestMethod.GET)
    public String queryCertification(@RequestParam Map<String,Object> params, HttpServletRequest request){
        List<TCertificateDTO> list = tCertificateService.queryListByNameAndIDCard(params);
        if(list == null || list.size() == 0){
            return "redirect:/h5/nodata";
        }
        request.setAttribute("list",list);
        return "cer-detail";
    }

    /**
     * 查询专家列表
     */
    @ResponseBody
    @GetMapping("queryExpertList/{id}")
    public Result<List<TNewsDTO>> queryExpertList(@PathVariable Long id){

        List<TNewsDTO> list = tNewsService.queryExpertList(id);

        return new Result<List<TNewsDTO>>().ok(list);
    }

    /**
     * 查询专家详情
     */
    @ResponseBody
    @GetMapping("queryExpertInfo/{id}")
    public Result<TNewsDTO> queryExpertInfo(@PathVariable Long id){

        TNewsDTO tNewsDTO = tNewsService.get(id);

        return new Result<TNewsDTO>().ok(tNewsDTO);

    }

    /**
     *模块分类id获取单页数据
     */
    @ResponseBody
    @GetMapping("queryAbout/{categoryId}")
    public Result<TAboutDTO> queryAbout(@PathVariable Integer categoryId){
        TAboutDTO tAboutDTO = tAboutService.queryByCatgegoryId(categoryId);
        return new Result<TAboutDTO>().ok(tAboutDTO);
    }

    /**
     *保存到报名表
     */
    @ResponseBody
    @GetMapping("saveSign")
    public Result saveSign(TSignupRecordDTO signupRecordDTO){

        signupRecordService.save(signupRecordDTO);

        return new Result<>().ok(null);
    }

    @ResponseBody
    @RequestMapping(value = "/queryCer", method = RequestMethod.GET)
    public Result<TCertificateDTO> queryCer(@RequestParam Map<String,Object> params, HttpServletRequest request){
        List<TCertificateDTO> list = tCertificateService.queryListByNameAndIDCard(params);

        if(list != null && list.size() > 0){
            return new Result<TCertificateDTO>().ok(list.get(0));
        }else{
            return new Result<TCertificateDTO>().error("查询不到该证书");
        }
    }

    /**
     * @param id
     * @return
     */
    @ResponseBody
    @GetMapping("/queryCerById/{id}")
    public Result<List<TCertificateDTO>> queryCerById(@PathVariable Long id){
        TCertificateDTO tCertificateDTO = tCertificateService.get(id);
        if(tCertificateDTO != null){

            List<TCertificateDTO> list = tCertificateService.queryListForResult(tCertificateDTO.getName(),tCertificateDTO.getIdCard());

            return new Result<List<TCertificateDTO>>().ok(list);
        }else{
            return new Result<List<TCertificateDTO>>().error("查询不到该证书");
        }

    }

    @ResponseBody
    @GetMapping("/queryCerImg/{id}")
    public Result<TCertificateDTO> queryCerImg(@PathVariable Long id){
        TCertificateDTO tCertificateDTO = tCertificateService.get(id);
        if(tCertificateDTO != null){

            return new Result<TCertificateDTO>().ok(tCertificateDTO);
        }else{
            return new Result<TCertificateDTO>().error("查询不到该证书");
        }

    }

    @ResponseBody
    @GetMapping("/queryRegion")
    public Result<List<SysRegionDTO>> queryRegion(){
        List<SysRegionDTO> list = sysRegionService.queryTreeList();

        List<SysRegionDTO> treeList = list.stream().filter(item -> item.getTreeLevel() == 1)
                .peek(child -> {
                    child.setChildren(this.findNodesTree(child, list));
                }).collect(Collectors.toList());

        return new Result<List<SysRegionDTO>>().ok(treeList);
    }
    private List<SysRegionDTO> findNodesTree(SysRegionDTO dto,List<SysRegionDTO> list){
        List<SysRegionDTO> children = list.stream().filter(child -> dto.getId().longValue() == child.getPid().longValue())
                .peek(child -> {
                    child.setChildren(findNodesTree(child, list));
                })
                .peek(child -> {
                    if (child.getChildren() == null || child.getChildren().size() == 0) child.setChildren(null);
                })
                .collect(Collectors.toList());
        return children;
    }


    /**
     * 根据分类ID查询地址列表
     */
    @ResponseBody
    @GetMapping("queryAddress/{categoryId}")
    public Result<List<TAddressEntity>> queryAddress(@PathVariable Integer categoryId){
        List<TAddressEntity> list = tAddressService.queryByCatgegoryId(categoryId);
        return new Result<List<TAddressEntity>>().ok(list);
    }



}
